"""
MiniCoder CLI 主入口模块

提供命令行接口，支持单次对话和交互式会话。
"""

import os
import sys
import re
from pathlib import Path
from typing import List, Optional

try:
    import click
    from rich.console import Console
    from rich.panel import Panel
    from rich.text import Text
    from rich.syntax import Syntax
    from rich.markdown import Markdown
    from rich.rule import Rule
    from rich.columns import Columns
    from rich.padding import Padding
    from rich.console import Group
    from rich.table import Table
except ImportError as e:
    print(f"错误: 缺少必要的依赖包: {e}")
    print("请运行: pip install click rich openai requests pyyaml")
    sys.exit(1)

from . import __version__

# 延迟导入，避免循环依赖
console = Console()


def _generate_with_typing_effect(ai_model, prompt: str, stream: bool, verbose: bool) -> str:
    """
    使用打字机效果生成响应
    
    Args:
        ai_model: AI模型实例
        prompt: 提示词
        stream: 是否使用流式API
        verbose: 是否显示详细信息
        
    Returns:
        生成的响应文本
    """
    console.print("\n[bold green]🤖 AI 响应:[/bold green]")
    console.print()
    
    # 定义回调函数
    def typing_callback(chunk: str):
        # 使用标准输出，避免Rich的缓冲问题
        import sys
        sys.stdout.write(chunk)
        sys.stdout.flush()
    
    # 使用回调函数生成响应
    try:
        response = ai_model.generate_with_callback(prompt, typing_callback, stream=stream)
        console.print()  # 换行
        
        if verbose:
            console.print(f"[dim]📊 响应长度: {len(response)} 字符[/dim]")
            console.print(f"[dim]⏱️ 响应时间: 已完成[/dim]")
        
        return response
    except Exception as e:
        console.print(f"[red]打字机效果出错: {e}[/red]")
        import traceback
        traceback.print_exc()
        return ""


def format_ai_response(response: str) -> str:
    """
    格式化AI响应，检测并高亮代码块
    
    Args:
        response: AI的原始响应文本
        
    Returns:
        格式化后的响应文本
    """
    # 检测代码块模式：```language\ncode\n```
    code_block_pattern = r'```(\w+)?\n(.*?)```'
    
    def replace_code_block(match):
        language = match.group(1) or 'text'
        code = match.group(2).strip()
        
        try:
            # 尝试使用Rich的语法高亮
            syntax = Syntax(code, language, theme="monokai", line_numbers=True)
            return str(syntax)
        except:
            # 如果语法高亮失败，使用简单的代码块格式
            return f"\n[bold cyan]代码块 ({language}):[/bold cyan]\n[dim]{code}[/dim]\n"
    
    # 替换代码块
    formatted = re.sub(code_block_pattern, replace_code_block, response, flags=re.DOTALL)
    
    # 检测内联代码：`code`
    inline_code_pattern = r'`([^`]+)`'
    formatted = re.sub(inline_code_pattern, r'[bold cyan]\1[/bold cyan]', formatted)
    
    return formatted


def create_loading_animation(message: str = "正在处理..."):
    """创建加载动画"""
    return console.status(f"[bold green]{message}[/bold green]", spinner="dots")


def print_error(message: str, details: str = None):
    """打印错误信息"""
    error_panel = Panel(
        f"[bold red]❌ {message}[/bold red]\n\n[dim]{details}[/dim]" if details else f"[bold red]❌ {message}[/bold red]",
        border_style="red",
        title="错误",
        title_align="left"
    )
    console.print(error_panel)


def print_success(message: str):
    """打印成功信息"""
    success_panel = Panel(
        f"[bold green]✅ {message}[/bold green]",
        border_style="green",
        title="成功",
        title_align="left"
    )
    console.print(success_panel)


def print_banner() -> None:
    """打印欢迎横幅"""
    banner_text = Text("MiniCoder CLI", style="bold blue")
    version_text = Text(f"v{__version__}", style="dim")
    subtitle = Text("轻量级、高效且可扩展的命令行AI编程助手", style="italic")
    
    panel = Panel(
        f"{banner_text}\n{version_text}\n\n{subtitle}",
        border_style="blue",
        padding=(1, 2)
    )
    console.print(panel)


@click.group(invoke_without_command=True)
@click.option(
    "--version",
    is_flag=True,
    help="显示版本信息"
)
@click.option(
    "--config",
    type=click.Path(exists=True, path_type=Path),
    help="指定配置文件路径"
)
@click.option(
    "--verbose",
    is_flag=True,
    help="启用详细输出模式"
)
@click.pass_context
def main(
    ctx: click.Context,
    version: bool,
    config: Optional[Path],
    verbose: bool
) -> None:
    """
    MiniCoder CLI - 轻量级、高效且可扩展的命令行AI编程助手
    
    类似Gemini CLI的命令结构，支持chat、generate、config等子命令。
    """
    # 显示版本信息
    if version:
        console.print(f"MiniCoder CLI v{__version__}")
        return
    
    # 如果没有子命令，默认启动交互式会话
    if not ctx.invoked_subcommand:
        try:
            from .utils.config import Config
            from .interactive import InteractiveSession
            
            # 加载配置
            cfg = Config(config_path=config)
            if verbose:
                console.print(f"[dim]📁 配置文件: {cfg.config_path}[/dim]")
                console.print(f"[dim]🔧 默认提供商: {cfg.get_provider()}[/dim]")
                console.print(f"[dim]🤖 默认模型: {cfg.get_model()}[/dim]")
            
            print_banner()
            
            # 显示会话信息
            session_info = Panel(
                "[bold]💬 交互式会话模式[/bold]\n\n"
                "• 输入 [bold cyan]help[/bold cyan] 查看可用命令\n"
                "• 输入 [bold cyan]quit[/bold cyan] 或 [bold cyan]exit[/bold cyan] 退出\n"
                "• 输入 [bold cyan]clear[/bold cyan] 清屏\n"
                "• 输入 [bold cyan]config[/bold cyan] 查看当前配置\n"
                "• 使用 [bold cyan]/provider[/bold cyan] 切换AI提供商\n"
                "• 使用 [bold cyan]/model[/bold cyan] 切换AI模型\n\n"
                "[dim]💡 提示: 使用 'minicoder --help' 查看所有命令选项[/dim]",
                title="🚀 会话已启动",
                border_style="green",
                padding=(1, 2)
            )
            console.print(session_info)
            console.print()
            
            session = InteractiveSession(cfg, stream=False, agent_mode=True)
            session.start()
            
        except KeyboardInterrupt:
            console.print("\n[yellow]⚠️ 会话已中断[/yellow]")
        except Exception as e:
            print_error("会话启动失败", str(e))
            sys.exit(1)


@main.command()
@click.option(
    "--model",
    help="指定使用的AI模型"
)
@click.option(
    "--provider",
    type=click.Choice(["openrouter", "ollama", "siliconflow"]),
    help="指定AI服务提供商"
)
@click.option(
    "--stream",
    is_flag=True,
    help="启用流式输出（逐字符显示）"
)
@click.option(
    "--agent/--no-agent",
    default=True,
    help="启用/禁用 Agent 模式（默认启用）"
)
@click.option(
    "--verbose",
    is_flag=True,
    help="启用详细输出模式"
)
@click.pass_context
def chat(
    ctx: click.Context,
    model: Optional[str],
    provider: Optional[str],
    stream: bool,
    agent: bool,
    verbose: bool
) -> None:
    """启动交互式对话会话"""
    try:
        from .utils.config import Config
        from .interactive import InteractiveSession
        
        # 获取全局配置路径
        config_path = ctx.parent.params.get('config')
        cfg = Config(config_path=config_path)
        
        if verbose:
            console.print(f"[dim]📁 配置文件: {cfg.config_path}[/dim]")
            console.print(f"[dim]🔧 默认提供商: {cfg.get_provider()}[/dim]")
            console.print(f"[dim]🤖 默认模型: {cfg.get_model()}[/dim]")
        
        # 如果指定了模型或提供商，更新配置
        if model:
            cfg.set_model(model)
            if verbose:
                console.print(f"[dim]🔄 切换到模型: {model}[/dim]")
        if provider:
            cfg.set_provider(provider)
            if verbose:
                console.print(f"[dim]🔄 切换到提供商: {provider}[/dim]")
        
        print_banner()
        
        # 显示会话信息
        session_info = Panel(
            "[bold]💬 交互式会话模式[/bold]\n\n"
            "• 输入 [bold cyan]help[/bold cyan] 查看可用命令\n"
            "• 输入 [bold cyan]quit[/bold cyan] 或 [bold cyan]exit[/bold cyan] 退出\n"
            "• 输入 [bold cyan]clear[/bold cyan] 清屏\n"
            "• 输入 [bold cyan]config[/bold cyan] 查看当前配置\n"
            "• 使用 [bold cyan]/provider[/bold cyan] 切换AI提供商\n"
            "• 使用 [bold cyan]/model[/bold cyan] 切换AI模型",
            title="🚀 会话已启动",
            border_style="green",
            padding=(1, 2)
        )
        console.print(session_info)
        console.print()
        
        session = InteractiveSession(cfg, stream=stream, agent_mode=agent)
        session.start()
        
    except KeyboardInterrupt:
        console.print("\n[yellow]⚠️ 会话已中断[/yellow]")
    except Exception as e:
        print_error("会话启动失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "-p", "--prompt",
    required=True,
    help="要发送的提示词"
)
@click.option(
    "--include",
    multiple=True,
    help="包含文件内容到上下文中"
)
@click.option(
    "--model",
    help="指定使用的AI模型"
)
@click.option(
    "--provider",
    type=click.Choice(["openrouter", "ollama", "siliconflow"]),
    help="指定AI服务提供商"
)
@click.option(
    "--stream",
    is_flag=True,
    help="启用流式输出（逐字符显示）"
)
@click.option(
    "--verbose",
    is_flag=True,
    help="启用详细输出模式"
)
@click.pass_context
def generate(
    ctx: click.Context,
    prompt: str,
    include: tuple,
    model: Optional[str],
    provider: Optional[str],
    stream: bool,
    verbose: bool
) -> None:
    """单次生成AI响应"""
    try:
        from .utils.config import Config
        from .core.prompt_builder import PromptBuilder
        from .ai import ModelFactory
        
        # 获取全局配置路径
        config_path = ctx.parent.params.get('config')
        cfg = Config(config_path=config_path)
        
        if verbose:
            console.print(f"[dim]📁 配置文件: {cfg.config_path}[/dim]")
            console.print(f"[dim]🔧 默认提供商: {cfg.get_provider()}[/dim]")
            console.print(f"[dim]🤖 默认模型: {cfg.get_model()}[/dim]")
        
        # 如果指定了模型或提供商，更新配置
        if model:
            cfg.set_model(model)
            if verbose:
                console.print(f"[dim]🔄 切换到模型: {model}[/dim]")
        if provider:
            cfg.set_provider(provider)
            if verbose:
                console.print(f"[dim]🔄 切换到提供商: {provider}[/dim]")
        
        if verbose:
            console.print(f"[dim]📝 原始提示词: {prompt}[/dim]")
            if include:
                console.print(f"[dim]📁 包含文件: {', '.join(include)}[/dim]")
        
        # 创建AI模型实例
        ai_model = ModelFactory.create_model(cfg)
        if verbose:
            console.print(f"[dim]🤖 使用AI模型: {type(ai_model).__name__}[/dim]")
        
        # 构建提示词
        prompt_builder = PromptBuilder()
        final_prompt = prompt_builder.build_prompt(
            prompt=prompt,
            context_files=list(include)
        )
        
        if verbose:
            console.print(f"[dim]🔧 构建后提示词长度: {len(final_prompt)} 字符[/dim]")
        
        # 发送请求
        if stream:
            # 流式输出（打字机效果）
            response = _generate_with_typing_effect(ai_model, final_prompt, True, verbose)
        else:
            # 普通输出
            loading_msg = "🤖 正在生成AI响应..."
            with create_loading_animation(loading_msg):
                response = ai_model.generate(final_prompt, stream=False)
            
            # 显示响应
            console.print("\n[bold green]🤖 AI 响应:[/bold green]")
            
            if verbose:
                console.print(f"[dim]📊 响应长度: {len(response)} 字符[/dim]")
                console.print(f"[dim]⏱️ 响应时间: 已完成[/dim]")
            
            # 直接输出响应，让Rich自动处理格式
            console.print(response)
        
    except Exception as e:
        print_error("AI响应生成失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "-d", "--description",
    required=True,
    help="项目描述"
)
@click.option(
    "--output-dir",
    type=click.Path(path_type=Path),
    default=".",
    help="输出目录（默认当前目录）"
)
@click.option(
    "--analyze-only",
    is_flag=True,
    help="仅分析项目需求，不生成文件"
)
@click.option(
    "--verbose",
    is_flag=True,
    help="启用详细输出模式"
)
@click.pass_context
def generate(
    ctx: click.Context,
    description: str,
    output_dir: Path,
    analyze_only: bool,
    verbose: bool
) -> None:
    """智能生成项目"""
    try:
        from .core.project_analyzer import ProjectAnalyzer
        from .core.project_generator import ProjectGenerator
        
        console.print(f"[bold]🔍 分析项目需求: {description}[/bold]")
        
        # 分析项目需求
        analyzer = ProjectAnalyzer()
        project_info, tasks = analyzer.analyze_and_generate_tasks(description)
        
        # 显示分析结果
        summary = analyzer.get_project_summary(project_info)
        console.print(Panel(summary, title="📋 项目分析结果", border_style="blue"))
        
        if analyze_only:
            console.print("[yellow]仅分析模式，不生成文件[/yellow]")
            return
        
        # 生成项目文件
        generator = ProjectGenerator()
        generated_files = generator.generate_project(project_info, str(output_dir))
        
        # 显示生成结果
        if generated_files:
            summary = generator.generate_project_summary(project_info, generated_files)
            console.print(Panel(summary, title="🎉 项目生成完成", border_style="green"))
        else:
            console.print("[red]❌ 项目生成失败[/red]")
            
    except Exception as e:
        print_error("项目生成失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "--env-vars",
    is_flag=True,
    help="显示支持的环境变量"
)
@click.pass_context
def config(ctx: click.Context, env_vars: bool) -> None:
    """显示当前配置信息"""
    try:
        from .utils.config import Config
        
        # 获取全局配置路径
        config_path = ctx.parent.params.get('config')
        cfg = Config(config_path=config_path)
        
        if env_vars:
            # 显示支持的环境变量
            env_table = Table(title="🌍 支持的环境变量", show_header=True, header_style="bold magenta")
            env_table.add_column("环境变量", style="cyan", no_wrap=True)
            env_table.add_column("说明", style="green")
            
            supported_vars = Config.get_supported_env_vars()
            for var, description in supported_vars.items():
                env_table.add_row(var, description)
            
            console.print(env_table)
            console.print("\n[dim]💡 提示: 环境变量会覆盖配置文件中的设置[/dim]")
            return
        
        # 创建配置表格
        table = Table(title="📋 MiniCoder CLI 配置信息", show_header=True, header_style="bold magenta")
        table.add_column("配置项", style="cyan", no_wrap=True)
        table.add_column("值", style="green")
        table.add_column("来源", style="dim")
        
        # 检查环境变量覆盖情况
        provider = cfg.get_provider()
        model = cfg.get_model()
        api_key = cfg.get_api_key()
        base_url = cfg.get_base_url()
        
        # 显示提供商信息
        provider_source = "环境变量" if os.getenv("MINICODER_DEFAULT_PROVIDER") else "配置文件"
        table.add_row("默认提供商", provider, provider_source)
        
        # 显示模型信息
        model_env_var = f"MINICODER_{provider.upper()}_MODEL"
        model_source = "环境变量" if os.getenv(model_env_var) else "配置文件"
        table.add_row("默认模型", model, model_source)
        
        # 显示API密钥信息
        api_key_env_var = f"MINICODER_{provider.upper()}_API_KEY"
        api_key_source = "环境变量" if os.getenv(api_key_env_var) else "配置文件"
        api_key_display = "已设置" if api_key else "未设置"
        table.add_row("API密钥", api_key_display, api_key_source)
        
        # 显示基础URL信息
        base_url_env_var = f"MINICODER_{provider.upper()}_BASE_URL"
        base_url_source = "环境变量" if os.getenv(base_url_env_var) else "配置文件"
        table.add_row("API基础URL", base_url, base_url_source)
        
        table.add_row("配置文件", str(cfg.config_path), "系统")
        
        console.print(table)
        console.print("\n[dim]💡 提示: 使用 --env-vars 查看所有支持的环境变量[/dim]")
        
    except Exception as e:
        print_error("配置读取失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "--list",
    "list_tools",
    is_flag=True,
    help="列出所有可用工具"
)
@click.option(
    "--info",
    help="显示指定工具的详细信息"
)
@click.option(
    "--enabled-only",
    is_flag=True,
    help="只显示启用的工具"
)
@click.option(
    "--search",
    help="搜索工具"
)
@click.pass_context
def tools(ctx: click.Context, list_tools: bool, info: Optional[str], 
         enabled_only: bool, search: Optional[str]) -> None:
    """管理可用工具"""
    try:
        from .tools import ToolManager
        
        # 获取全局配置路径
        config_path = ctx.parent.params.get('config')
        tool_manager = ToolManager()
        
        if info:
            # 显示工具详细信息
            tool_info = tool_manager.get_tool_info(info)
            if tool_info:
                from rich.panel import Panel
                from rich.json import JSON
                
                info_panel = Panel(
                    JSON.from_data(tool_info, indent=2),
                    title=f"🔧 工具信息: {info}",
                    border_style="blue"
                )
                console.print(info_panel)
            else:
                console.print(f"[red]工具不存在: {info}[/red]")
        
        elif search:
            # 搜索工具
            matching_tools = tool_manager.search_tools(search)
            if matching_tools:
                table = tool_manager.create_tools_table(enabled_only)
                console.print(f"\n[bold]搜索结果: '{search}'[/bold]")
                console.print(table)
            else:
                console.print(f"[yellow]未找到匹配的工具: {search}[/yellow]")
        
        elif list_tools:
            # 列出工具
            table = tool_manager.create_tools_table(enabled_only)
            console.print(table)
            
            # 显示统计信息
            stats = tool_manager.get_tool_statistics()
            from rich.panel import Panel
            stats_panel = Panel(
                f"总工具数: {stats['total_tools']}\n"
                f"启用工具: {stats['enabled_tools']}\n"
                f"禁用工具: {stats['disabled_tools']}\n"
                f"执行次数: {stats['execution_stats']['total_executions']}\n"
                f"成功率: {stats['execution_stats']['success_rate']:.1f}%",
                title="📊 工具统计",
                border_style="green"
            )
            console.print(stats_panel)
        
        else:
            # 默认显示工具列表
            table = tool_manager.create_tools_table(enabled_only)
            console.print(table)
            console.print("\n[dim]使用 'minicoder tools --help' 查看所有选项[/dim]")
        
    except Exception as e:
        print_error("工具管理失败", str(e))
        sys.exit(1)


@main.command()
@click.argument('tool_name')
@click.option(
    "--params",
    help="工具参数（JSON 格式）"
)
@click.option(
    "--verbose",
    is_flag=True,
    help="显示详细输出"
)
@click.pass_context
def run_tool(ctx: click.Context, tool_name: str, params: Optional[str], verbose: bool) -> None:
    """执行指定工具"""
    try:
        from .tools import ToolManager
        import json
        
        tool_manager = ToolManager()
        
        # 解析参数
        tool_params = {}
        if params:
            try:
                tool_params = json.loads(params)
            except json.JSONDecodeError as e:
                console.print(f"[red]参数格式错误: {e}[/red]")
                return
        
        if verbose:
            console.print(f"[dim]执行工具: {tool_name}[/dim]")
            console.print(f"[dim]参数: {tool_params}[/dim]")
        
        # 执行工具
        result = tool_manager.execute_tool(tool_name, **tool_params)
        
        if result.success:
            console.print(f"[green]✓[/green] 工具执行成功")
            if result.data:
                if verbose:
                    from rich.json import JSON
                    console.print(JSON.from_data(result.data, indent=2))
                else:
                    console.print(result.message)
        else:
            console.print(f"[red]✗[/red] 工具执行失败: {result.error}")
        
        if verbose:
            console.print(f"[dim]执行时间: {result.execution_time:.2f}s[/dim]")
        
    except Exception as e:
        print_error("工具执行失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "--pattern",
    required=True,
    help="搜索模式"
)
@click.option(
    "--directory",
    default=".",
    help="搜索目录（默认当前目录）"
)
@click.option(
    "--recursive",
    is_flag=True,
    default=True,
    help="递归搜索子目录"
)
@click.option(
    "--file-types",
    help="文件类型过滤（逗号分隔，如 .py,.js,.ts）"
)
@click.option(
    "--case-sensitive",
    is_flag=True,
    help="区分大小写"
)
@click.option(
    "--max-results",
    default=50,
    help="最大结果数量"
)
def search(pattern: str, directory: str, recursive: bool, file_types: Optional[str], 
          case_sensitive: bool, max_results: int) -> None:
    """搜索文件"""
    try:
        from .tools import ToolManager
        
        tool_manager = ToolManager()
        
        # 解析文件类型
        types_list = []
        if file_types:
            types_list = [t.strip() for t in file_types.split(',') if t.strip()]
        
        # 执行搜索
        result = tool_manager.execute_tool('file_search', 
                                         pattern=pattern,
                                         directory=directory,
                                         recursive=recursive,
                                         file_types=types_list,
                                         case_sensitive=case_sensitive,
                                         max_results=max_results)
        
        if result.success:
            console.print(f"[green]✓[/green] {result.message}")
            if result.data and result.data.get('files'):
                from rich.table import Table
                
                table = Table(show_header=True, header_style="bold magenta")
                table.add_column("文件", style="cyan")
                table.add_column("大小", style="green")
                table.add_column("修改时间", style="dim")
                
                for file_info in result.data['files'][:20]:  # 只显示前20个
                    table.add_row(
                        file_info['relative_path'],
                        f"{file_info['size']} bytes",
                        file_info['modified'][:19]  # 只显示日期时间部分
                    )
                
                console.print(table)
                
                if len(result.data['files']) > 20:
                    console.print(f"[dim]... 还有 {len(result.data['files']) - 20} 个文件[/dim]")
        else:
            console.print(f"[red]✗[/red] 搜索失败: {result.error}")
        
    except Exception as e:
        print_error("文件搜索失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "--query",
    required=True,
    help="搜索查询"
)
@click.option(
    "--directory",
    default=".",
    help="搜索目录（默认当前目录）"
)
@click.option(
    "--file-types",
    help="文件类型过滤（逗号分隔）"
)
@click.option(
    "--case-sensitive",
    is_flag=True,
    help="区分大小写"
)
@click.option(
    "--context-lines",
    default=2,
    help="显示上下文行数"
)
def code_search(query: str, directory: str, file_types: Optional[str], 
               case_sensitive: bool, context_lines: int) -> None:
    """在代码中搜索文本"""
    try:
        from .tools import ToolManager
        
        tool_manager = ToolManager()
        
        # 解析文件类型
        types_list = []
        if file_types:
            types_list = [t.strip() for t in file_types.split(',') if t.strip()]
        
        # 执行代码搜索
        result = tool_manager.execute_tool('code_search',
                                         query=query,
                                         directory=directory,
                                         file_types=types_list,
                                         case_sensitive=case_sensitive,
                                         context_lines=context_lines)
        
        if result.success:
            console.print(f"[green]✓[/green] {result.message}")
            if result.data and result.data.get('results'):
                for file_result in result.data['results'][:10]:  # 只显示前10个文件
                    console.print(f"\n[bold cyan]{file_result['relative_path']}[/bold cyan]")
                    
                    for match in file_result['matches'][:5]:  # 每个文件最多显示5个匹配
                        console.print(f"  [dim]第 {match['line_number']} 行:[/dim] {match['content']}")
                        
                        if match.get('context'):
                            for ctx in match['context']:
                                if ctx['is_match']:
                                    console.print(f"    [yellow]→ {ctx['line_number']}: {ctx['content']}[/yellow]")
                                else:
                                    console.print(f"    [dim]  {ctx['line_number']}: {ctx['content']}[/dim]")
        else:
            console.print(f"[red]✗[/red] 代码搜索失败: {result.error}")
        
    except Exception as e:
        print_error("代码搜索失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "--directory",
    default=".",
    help="项目目录（默认当前目录）"
)
@click.option(
    "--checks",
    help="检查类型（逗号分隔，如 complexity,style,security）"
)
def analyze(directory: str, checks: Optional[str]) -> None:
    """分析代码质量"""
    try:
        from .tools import ToolManager
        
        tool_manager = ToolManager()
        
        # 解析检查类型
        checks_list = ['complexity', 'style', 'security']
        if checks:
            checks_list = [c.strip() for c in checks.split(',') if c.strip()]
        
        # 执行代码质量分析
        result = tool_manager.execute_tool('code_quality',
                                         directory=directory,
                                         checks=checks_list)
        
        if result.success:
            console.print(f"[green]✓[/green] {result.message}")
            if result.data:
                from rich.panel import Panel
                from rich.json import JSON
                
                analysis_panel = Panel(
                    JSON.from_data(result.data, indent=2),
                    title="📊 代码质量分析结果",
                    border_style="blue"
                )
                console.print(analysis_panel)
        else:
            console.print(f"[red]✗[/red] 代码分析失败: {result.error}")
        
    except Exception as e:
        print_error("代码分析失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "--directory",
    default=".",
    help="项目目录（默认当前目录）"
)
@click.option(
    "--max-depth",
    default=3,
    help="最大显示深度"
)
def project(directory: str, max_depth: int) -> None:
    """分析项目结构"""
    try:
        from .tools import ToolManager
        
        tool_manager = ToolManager()
        
        # 执行项目分析
        result = tool_manager.execute_tool('project_analyzer',
                                         directory=directory,
                                         max_depth=max_depth)
        
        if result.success:
            console.print(f"[green]✓[/green] {result.message}")
            if result.data:
                from rich.panel import Panel
                from rich.json import JSON
                
                project_panel = Panel(
                    JSON.from_data(result.data, indent=2),
                    title="📁 项目分析结果",
                    border_style="green"
                )
                console.print(project_panel)
        else:
            console.print(f"[red]✗[/red] 项目分析失败: {result.error}")
        
    except Exception as e:
        print_error("项目分析失败", str(e))
        sys.exit(1)


@main.command()
@click.option(
    "--config",
    type=click.Path(path_type=Path),
    help="配置文件路径"
)
@click.option(
    "--project",
    is_flag=True,
    help="初始化项目工作目录（包含会话持久化）"
)
def init(config: Optional[Path], project: bool) -> None:
    """初始化配置文件或项目工作目录"""
    try:
        from .utils.config import Config
        
        if project:
            # 初始化项目工作目录
            _init_project_directory()
        else:
            # 初始化全局配置文件
            Config.create_default_config(config)
            print_success("配置文件创建成功！")
            
            # 显示下一步操作指南
            next_steps = Panel(
                "[bold]📝 下一步操作:[/bold]\n\n"
                "1. 编辑配置文件并设置您的API密钥\n"
                "2. 运行 [bold cyan]minicoder config[/bold cyan] 查看配置\n"
                "3. 运行 [bold cyan]minicoder -p '你好'[/bold cyan] 测试连接\n"
                "4. 运行 [bold cyan]minicoder[/bold cyan] 启动交互式会话\n"
                "5. 运行 [bold cyan]minicoder init --project[/bold cyan] 初始化项目工作目录",
                title="🚀 开始使用",
                border_style="blue",
                padding=(1, 2)
            )
            console.print(next_steps)
        
    except Exception as e:
        print_error("初始化失败", str(e))
        sys.exit(1)


def _init_project_directory() -> None:
    """初始化项目工作目录"""
    import os
    from pathlib import Path
    
    # 创建 .minicoder 目录
    minicoder_dir = Path(".minicoder")
    minicoder_dir.mkdir(exist_ok=True)
    
    # 创建子目录
    (minicoder_dir / "sessions").mkdir(exist_ok=True)
    (minicoder_dir / "checkpoints").mkdir(exist_ok=True)
    (minicoder_dir / "generated").mkdir(exist_ok=True)
    
    # 创建项目配置文件
    project_config = {
        "project": {
            "name": Path.cwd().name,
            "created": str(Path.cwd()),
            "description": "MiniCoder CLI 项目工作目录"
        },
        "session": {
            "auto_save": True,
            "max_history": 50,
            "checkpoint_interval": 10
        },
        "code_generation": {
            "auto_save_code": True,
            "code_output_dir": ".minicoder/generated",
            "backup_original": True
        }
    }
    
    import yaml
    config_file = minicoder_dir / "config.yaml"
    with open(config_file, 'w', encoding='utf-8') as f:
        yaml.dump(project_config, f, default_flow_style=False, allow_unicode=True)
    
    # 创建 .gitignore 条目
    gitignore_file = Path(".gitignore")
    gitignore_entry = "\n# MiniCoder CLI\n.minicoder/\n"
    
    if gitignore_file.exists():
        with open(gitignore_file, 'r', encoding='utf-8') as f:
            content = f.read()
        if ".minicoder/" not in content:
            with open(gitignore_file, 'a', encoding='utf-8') as f:
                f.write(gitignore_entry)
    else:
        with open(gitignore_file, 'w', encoding='utf-8') as f:
            f.write(f"# MiniCoder CLI{gitignore_entry}")
    
    print_success("项目工作目录初始化成功！")
    
    # 显示项目信息
    project_info = Panel(
        f"[bold]📁 项目目录:[/bold] {Path.cwd()}\n"
        f"[bold]🔧 配置文件:[/bold] {config_file}\n"
        f"[bold]💾 会话存储:[/bold] {minicoder_dir / 'sessions'}\n"
        f"[bold]📝 代码输出:[/bold] {minicoder_dir / 'generated'}\n"
        f"[bold]🔄 检查点:[/bold] {minicoder_dir / 'checkpoints'}\n\n"
        "[bold]✨ 新功能:[/bold]\n"
        "• 会话历史自动保存\n"
        "• 代码生成自动保存\n"
        "• 项目级上下文管理\n"
        "• 检查点恢复功能",
        title="🎉 项目初始化完成",
        border_style="green",
        padding=(1, 2)
    )
    console.print(project_info)




if __name__ == "__main__":
    main()
